package t2.server;

import java.util.concurrent.Callable;

import t2.server.xbee.XBeePort;

import com.rapplogic.xbee.api.AtCommand;
import com.rapplogic.xbee.api.AtCommandResponse;
import com.rapplogic.xbee.api.PacketListener;
import com.rapplogic.xbee.api.XBee;
import com.rapplogic.xbee.api.XBeeResponse;
import com.rapplogic.xbee.util.ByteUtils;

public class DoNI implements Callable<String> {
    boolean responseReceived;
    private String nodeIdentifier;
    int nop = 0;

    PacketListener NI = new PacketListener() {

        @Override
        public void processResponse(XBeeResponse response) {
            AtCommandResponse atResp = (AtCommandResponse) response;
            if (atResp.getCommand().equals("NI")) {
                setNodeIdentifier(ByteUtils.toString(atResp.getValue()));
                responseReceived = true;
            }
        }
    };

    @Override
    public String call() throws Exception {
        XBee xbee = XBeePort.getXBeePort().getXbee();
        xbee.addPacketListener(NI);
        xbee.sendAsynchronous(new AtCommand("NI"));
        do {
            Thread.sleep(1);
            nop++;
        }
        while (!responseReceived && nop < 6000);
        xbee.removePacketListener(NI);
        xbee.clearResponseQueue();


        return getNodeIdentifier();
    }

    public String getNodeIdentifier() {
        return nodeIdentifier;
    }

    public void setNodeIdentifier(String nodeIdentifier) {
        this.nodeIdentifier = nodeIdentifier;
    }

}
